import { defineStore } from 'pinia'
import { getStorage, setStorage, removeStorage } from '@/utils/storage'
import { adminLogin, userPermission } from '@/api';
import { wyLogin } from '@/api/wy';

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      userInfo: getStorage('userInfo') || {},
      token: getStorage('token') || '',
      permissions: [],
      _routesLoaded: false
    }
  },
  getters: {
    userId() {
      return this.userInfo?.user_id || null
    },
    username() {
      return this.userInfo?.name || ''
    },
    roleName() {
      return this.userInfo?.role_name || ''
    },
    departmentName() {
      return this.userInfo?.department_name || ''
    },
    departmentId() {
      return this.userInfo?.department_id || null
    },
    routesLoaded() {
      return this._routesLoaded
    },
    permissionList() {
      return this.permissions
    },
    isWyCompany() {
      return this.userInfo?.isWyCompany || false
    }
  },
  actions: {
    loginSuccess(data) {
      this.userInfo = data.user_info;
      this.token = data.token;
      setStorage('userInfo', this.userInfo);
      setStorage('token', this.token);
    },
    login(
      { userName, password }
    ) {
      return adminLogin({
        username: userName,
        password
      }).then(({ data }) => {
        if (data) {
          this.loginSuccess(data);
        }
      })
    },
    logout() {
      this.$reset();
      removeStorage('userInfo');
      removeStorage('token');
      window.location.replace('/#/login');
    },

    wyLogin({ login_code }) {
      return wyLogin({
        login_code,
      }).then(({ data }) => {
        if (data) {
          data.user_info = {
            user_id: data.company_id,
            name: data.company_name,
            isWyCompany: true,
          }
          this.loginSuccess(data);
        }
      })
    },

    async getPermissions() {
      if (this.userInfo.isWyCompany) {
        this.permissions = [
          { name: "WyView", title: "欠费数据查看" }
        ];
        return;
      }
      const { data } = await userPermission({ role_id: this.userInfo.role_id });
      if (data) {
        this.permissions = data;
      }
    },

    setRoutesLoaded(val) {
      this._routesLoaded = val;
    }
  }
})